import {Row, Col, Menu, Dropdown, Icon, Spin} from 'antd';
// import Row from '../../_antd1.11.2/Row'
// import Col from '../../_antd1.11.2/Col'
// import Menu from '../../_antd1.11.2/menu';
// import Dropdown from '../../_antd1.11.2/Dropdown';
// import Icon from '../../_antd1.11.2/Icon';
// import Spin from '../../_antd1.11.2/Spin';
// import cloneDeep from 'lodash/cloneDeep'
import isEqual from 'lodash/isEqual'
import WeaInputSearch from '../wea-input-search'
import WeaScroll from '../wea-scroll';
import WeaBrowserTree from '../base/wea-browser-single-tree/WeaBrowserTree';
import WeaDropMenu from '../wea-drop-menu';
import  WeaTools from '../wea-tools';
import debounce from 'lodash/debounce'

export default class Main extends React.Component {
    static defaultProps={
        topPrefix:'tree',
        dataUrl:'/api/hrm/base/getHrmSearchTree',
        loadUserUrl:`/api/hrm/base/getHrmSearchTree?isLoadUser=1`,
        rootKey: 'rootCompany'
    }

    constructor(props) {
        super(props);
        this.state = {
            height:0,
            companysDefault:props.companysDefault || '',
            companyDropMenu:props.companyDropMenu||[],
            treeData:props.firstClassTree||{},
            defaultExpandedKeys:props.defaultExpandedKeys||[],
            value:'',
            virtualCompanyid:'1',
            dataUrl:props.isLoadUser ? props.loadUserUrl : props.dataUrl,
            loading:!!props.loading,
            clearSelectedKeys:false,
            loading:false,
        };
        ['menuSelect','scrollheigth','getWfList','fetchData','treeNodeClick',
         'onFliterAll','onSearchChange','selectedKeysChange'].forEach( f => this[f]=this[f].bind(this));
    }
    scrollheigth(){
        const top = jQuery(".wea-org-tree .wea-org-tree-scroll").offset().top;
        const scrollheigth = document.documentElement.clientHeight - top - 15;
        jQuery(".wea-org-tree .wea-org-tree-scroll").height(scrollheigth);
    }
    getWfList(datas=[]){
        const arr = new Array();
        for (let i=0;i<datas.length;i++) {
            const data = datas[i];
                arr.push({
                    companyid:data.companyid,
                    name: data.name,
                    isVirtual:data.isVirtual,
                });
            }
        return arr;
    }
    fetchData(innerParams={},fetchDropMenu=true, outerParams = this.props.params){
        const {topPrefix}=this.props;
        const {dataUrl} = this.state;
        let searchParams = {...outerParams, ...innerParams};
        if(!this.props.firstClassTree){
            this.props.loading && this.setState({loading:true});
            WeaTools.callApi(dataUrl, 'GET',searchParams).then(data=>{
                const root = data.datas[this.props.rootKey];
                const id = root.id;
                this.setState(function(){
                    if(fetchDropMenu){
                        return {
                            treeData:root||{},
                            companyDropMenu:this.getWfList(data.companys)||[],
                            defaultExpandedKeys:`${topPrefix}0-${id}`,
                            loading:false,
                        }
                    }
                    return {
                        treeData:root||{},
                        defaultExpandedKeys:`${topPrefix}0-${id}`,
                        loading:false,
                    }
                })
            })
        }
    }
    componentDidMount(){
        let param = {};
        let {isLoadSubDepartment} = this.props;
        if (isLoadSubDepartment) {
            param.isLoadSubDepartment = 1;
        }
        this.fetchData(param);
        this.scrollheigth();
        jQuery(window).resize(() => {
		    this._reactInternalInstance !== undefined && this.scrollheigth();
		});
    }
    componentDidUpdate(prevProps,prevState){
        this.scrollheigth();
    }
    shouldComponentUpdate(nextProps, nextState) {
        return this.state.height !== nextState.height||
            this.state.value !== nextState.value||
            !isEqual(this.props.companyDropMenu,nextProps.companyDropMenu)||
            !isEqual(this.state.companyDropMenu,nextState.companyDropMenu)||
            !isEqual(this.state.treeData,nextState.treeData)||
            this.props.defaultExpandedKeys !== nextProps.defaultExpandedKeys||
            this.state.defaultExpandedKeys !== nextState.defaultExpandedKeys||
            this.state.companysDefault !== nextState.companysDefault||
            this.props.companysDefault !== nextProps.companysDefault

    }
    componentWillReceiveProps(nextProps){
        const {firstClassTree,defaultExpandedKeys, params} = this.props;
         if(this.props.companysDefault !== nextProps.companysDefault){
            this.setState({companysDefault:nextProps.companysDefault})
        }
        if(defaultExpandedKeys){
            if(defaultExpandedKeys !== nextProps.defaultExpandedKeys){
                this.setState({defaultExpandedKeys:nextProps.defaultExpandedKeys})
            }
        }
        if(firstClassTree){
            if(firstClassTree.companyid !== nextProps.firstClassTree.companyid){
                this.setState({treeData:nextProps.firstClassTree})
            }
            if(firstClassTree.companyid !== nextProps.firstClassTree.companyid ||
                firstClassTree.subs.length !== nextProps.firstClassTree.subs.length
             ){//暂时做这样的处理后续需要优化（切换虚拟公司or搜索）
                this.setState({treeData:nextProps.firstClassTree})
            }
        }
        if (!isEqual(nextProps.params, params)) {
            this.fetchData({}, true, nextProps.params);
        }
    }
    render() {
        const {topPrefix,datas,counts,countsType,url,firstClassTree,needDropMenu,needSearch,inputLeftDom,inputRightDom} = this.props;
        let {companysDefault,companyDropMenu,treeData,defaultExpandedKeys} = this.state;
        let compyInit = this.state.companysDefault.name;
        companyDropMenu&&companyDropMenu.forEach((item)=>{
            if(!compyInit && item.companyid == '1'){//获取初始公司name
                compyInit = item.name;
            }
        })
        return (
            <div className="wea-new-tree wea-org-tree">
             <Spin spinning={this.state.loading} size='large'>
                {needDropMenu &&
                     <WeaDropMenu
                        defaultMenu={compyInit}
                        dropMenu={companyDropMenu}
                        onSelect={this.menuSelect}
                    />
                }
               {needSearch &&
                <div className="wea-input-wraper">
                   <span onClick={this.onFliterAll.bind(this,'')} style={{"cursor":"pointer"}}>
                    {inputLeftDom ? <div  className='wea-org-tree-inputLeftDom' dangerouslySetInnerHTML={{__html:inputLeftDom}} /> : ''}
                   </span>
                   <WeaInputSearch onSearchChange={debounce(this.onSearchChange, 400).bind(this)} value={this.state.value}/>
                   {inputRightDom ? <div className='wea-org-tree-inputRightDom' dangerouslySetInnerHTML={{__html:inputRightDom}} /> : ''}
                </div>}
                <WeaScroll className="wea-org-tree-scroll" typeClass="scrollbar-macosx" >
                    <WeaBrowserTree
                        {...this.props}
                        dataUrl={this.state.dataUrl}
                        keyword={this.state.value}
                        type={this.props.isLoadSubDepartment?4:164}
                        browserTree={true}
                        checkable={false}
                        isMult={false}
                        treeData={treeData}
                        defaultExpandedKeys={[defaultExpandedKeys]}
                        componyParam={companysDefault.companyid}//刷新默认展开key用
                        selectedKeys={this.selectedKeysChange}
                        onSelect={this.treeNodeClick}
                    />
                </WeaScroll>
             </Spin>
            </div>
        );
    }
    selectedKeysChange(keys){

    }
    treeNodeClick(nodeObj){
        // console.log('nodeObj',nodeObj,this.Tree);
        if(typeof this.props.treeNodeClick === "function"){
            this.props.treeNodeClick(nodeObj);
        }
    }
    menuSelect(e){
        // console.log("onSelect",e);
        const {url,companysDefault,companyDropMenu} = this.state;
        let param = {virtualCompanyid: e.key};
        let {isLoadSubDepartment} = this.props;
        if (isLoadSubDepartment) {
            param.isLoadSubDepartment = 1;
        }
        this.fetchData(param, false);
        if(typeof this.props.onSelect == 'function'){
            this.props.onSelect(e);
        }
        if(typeof this.props.virtualCompanyid == 'function'){
            this.props.virtualCompanyid(e.key);
        }
        companyDropMenu&&companyDropMenu.forEach((item)=>{
            if(e.key == item.companyid){
                this.setState({
                    companysDefault:{companyid:e.key,name:item.name},
                });
            }
        })
        this.setState({
            virtualCompanyid:e.key,
            value:'',//清空树搜索条件
        });
    }
    onFliterAll() {
        // this.setState({clearSelectedKeys:true});
    	if(typeof this.props.onFliterAll == 'function'){
    		this.props.onFliterAll();
    	}
    }
    onSearchChange(v){
        let param = {virtualCompanyid:this.state.virtualCompanyid, keyword:v};
        let {isLoadSubDepartment} = this.props;
        if (isLoadSubDepartment) {
            param.isLoadSubDepartment = 1;
        }
        this.fetchData(param);
        if(typeof this.props.onSearchChange == 'function'){
            this.props.onSearchChange(v)
        }
        this.setState({value:v})
    }
}


